package com.lin.netty.module.future;

import io.netty.channel.EventLoop;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.util.concurrent.DefaultPromise;
import io.netty.util.concurrent.Promise;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;

/**
 * netty Promise 不仅有 netty Future 的功能，而且脱离了任务独立存在，只作为两个线程间传递结果的容器
 */
@Slf4j
public class NettyPromiseTest {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup();

        EventLoop eventLoop = eventLoopGroup.next();
        // 可以直接创建来接管eventLoop
        DefaultPromise<Integer> promise = new DefaultPromise<>(eventLoop);

//        eventLoop.submit(new Callable<Integer>() {
//            @Override
//            public Integer call() throws Exception {
//                log.debug("异步计算");
//                Thread.sleep(5000);
//                log.debug("异步计算完成");
//                return 99;
//            }
//        });

        eventLoop.submit(() -> {
            log.debug("异步计算");
            try {
                Thread.sleep(5000);
                System.out.println(1/0);
                log.debug("异步计算完成");
                promise.setSuccess(99);
            } catch (Exception e) {
                promise.setFailure(e);
            }

        });

        log.debug("同步等待结果");
//        promise.get()
        promise.sync();
        log.debug("结果是：{}", promise.getNow());
    }
}
